
package com.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Map;
import net.sf.json.JSONObject;

public class SocketService {
	public String connServer(Map<String, String> map,String ServerIP,int ServerPort) {
		String respXml = "";
		// 1.建立客户端socket连接，指定服务器位置及端口
		Socket socket = null;
		// 2.得到socket读写流
		OutputStream os = null;
		PrintWriter pw = null;
		// 输入流
		InputStream is = null;
		BufferedReader br = null;
		try {
			socket = new Socket();
		    socket.connect(new InetSocketAddress(ServerIP, ServerPort),10000);// 连接超时设置
			socket.setSoTimeout(20000); // 读写超时设置
			os = socket.getOutputStream();
			pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
			is = socket.getInputStream();

			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			// 3.利用流按照一定的操作，对socket进行读写操作
			String info = jsonObject(map);
			System.out.println("请求报文:\n"+info);
			pw.write(info);
			pw.flush();
			socket.shutdownOutput();
			// 接收服务器的相应
			String reply = null;
			while (!((reply = br.readLine()) == null)) {
				respXml += reply;
			}
			System.out.println("接到返回：\n" + respXml);
			socket.shutdownInput();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 4.关闭资源
				if (br != null) {
					br.close();
				}
				if (is != null) {
					is.close();
				}
				if (pw != null) {
					pw.close();
				}
				if (os != null) {
					os.close();
				}
				if (socket != null) {
					socket.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return respXml;
	}
	/**
	 * ********************************************************
	 * 
	 * @Title: jsonObject
	 * @Description:将对象转换成json字符串
	 * @param obj
	 * @return String
	 * @date 2013-12-12 上午11:11:20
	 ******************************************************** 
	 */
	protected static String jsonObject(Object obj) {

		String json = "";
		try {
			json = JSONObject.fromObject(obj).toString();
			return json;
		} catch (Exception e) {
			json = "{\"err\":\"" + "JsonObject is wrong" + "\"}";
			return json;
		}
	}
}

	